package com.macro.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.macro.enums.AppHttpCodeEnum;
import com.macro.mapper.UserMapper;
import com.macro.mapper.UserRoleMapper;
import com.macro.pojos.dto.ResponseResult;
import com.macro.pojos.dto.UserDto;
import com.macro.pojos.dto.UserUpdateDto;
import com.macro.pojos.pojo.User;
import com.macro.pojos.pojo.UserAndRole;
import com.macro.service.UserService;
import com.macro.utils.FastDFSClientUtil;
import com.macro.utils.MD5Utils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;
    @Autowired
    JavaMailSenderImpl mailSender;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private FastDFSClientUtil fastDFSClientUtil;


    @Override
    public ResponseResult enrollUser(UserDto userDto) {
        String salt ="zjy123";
        if (userDto.getUsername()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if (userDto.getPassword()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        } if (userDto.getTel()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        } if (userDto.getMailbox()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        String zjy123 = MD5Utils.encodeWithSalt(userDto.getPassword(), salt);
        userDto.setPassword(zjy123);
        User user = new User();
        BeanUtils.copyProperties(userDto,user);
        user.setSalt("zjy123");
        user.setRegisterTime(new Date());
        user.setIsDelete(false);
        int i = userMapper.insert(user);
        if (i==1){
            addUserRole(user.getId());
            return ResponseResult.okResult("注册成功");
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.FAIL);
    }

    @Override
    public ResponseResult goCode(String eml) {
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getMailbox,eml);
        List<User> users = userMapper.selectList(lambdaQueryWrapper);
        if (users.size()>=1){
            return ResponseResult.errorResult(500,"手机号已注册");
        }
        Random random = new Random();
        String result="";
        for (int i=0;i<6;i++)
        {
            result+=random.nextInt(10);
        }
        System.out.println(result);
        contextLoads(result,eml);
        redisTemplate.boundValueOps("code").set(result);
        redisTemplate.expire("code",60, TimeUnit.MILLISECONDS);
        return ResponseResult.okResult("验证码发送成功");
    }

    @Override
    public ResponseResult VerificationCode(String code) {
        String code1 =(String) redisTemplate.boundValueOps("code").get();
        System.out.println(code1);
        if (code==null){
            return ResponseResult.errorResult(500,"验证码不存在");
        }else if (code1.equals(code)){
            return ResponseResult.okResult("验证成功");
        }else {
            return ResponseResult.errorResult(500,"验证码不对");
        }
    }

    @Override
    public ResponseResult upload(MultipartFile file) throws IOException {
        if (file==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        String url = fastDFSClientUtil.uploadFile(file);
        System.out.println(url);
        return ResponseResult.okResult(url);
    }

    @Override
    public ResponseResult deleteUser(Integer id) {
        if (id==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        UserAndRole userAndRole = userRoleMapper.findByUserId(id);
        if (userAndRole==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        userAndRole.setIsDelete(true);
        userRoleMapper.updateIsDelete(userAndRole);
        Boolean t = true;
        User user = userMapper.selectById(id);
        if (user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }
        user.setIsDelete(true);
        userMapper.updateById(user);
return ResponseResult.okResult("删除成功");
    }

    @Override
    public ResponseResult updateUser(UserUpdateDto userUpdateDto) {
        if (userUpdateDto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }
        User user = userMapper.selectById(userUpdateDto.getId());
        if (user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        BeanUtils.copyProperties(userUpdateDto,user);
        userMapper.updateById(user);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    public Integer addUserRole(Integer userId){
        if (userId==null){
            return 0;
        }
        Date date = new Date();
        Boolean fase = false;
        int insert = userRoleMapper.insert(userId,date,fase);
        if (insert==1){
            System.out.println("添加中间表成功");
            return 200;
        }
        return 500;
    }

    public void contextLoads(String result,String eml) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setSubject("某某软件");
        message.setText("某某软件发送的验证码："+result);
        message.setTo(eml);
        message.setFrom("1410204893@qq.com");
        mailSender.send(message);
        System.out.println("验证码发送成功");
    }
}
